const express = require('express');
const router = express.Router();
const jwt = require('jsonwebtoken');
const { userModel } = require('../model/model');

// token验证登录接口
router.post('/login', (req, res) => {
  const { username, password } = req.body;
  // 这里应有真实用户校验逻辑，示例仅做演示
  if (username === 'admin' && password === '123456') {
    const secretKey = 'your_secret_key';
    const token = jwt.sign({ username }, secretKey, { expiresIn: '1h' });
    res.json({ status: 'success', token });
  } else {
    res.status(401).json({ status: 'error', message: '用户名或密码错误' });
  }
});

// 获取用户关注列表
router.get('/following', async (req, res) => {
  try {
    const { userId } = req.query;

    if (!userId) {
      return res.status(400).json({ message: '请提供用户ID' });
    }

    // 查找用户
    const user = await userModel.findById(userId);
    if (!user) {
      return res.status(404).json({ message: '用户不存在' });
    }

    // 获取关注的用户ID列表
    const followingIds = user.following;
    if (!followingIds || followingIds.length === 0) {
      return res.status(200).json({ following: [] });
    }

    // 查找关注的用户详情
    const followingUsers = await userModel.find({ _id: { $in: followingIds } });

    // 格式化返回结果
    const formattedFollowing = followingUsers.map(user => ({
      _id: user._id,
      username: user.username,
      avatarImage: user.avatarImage,
      isAvatarImageSet: user.isAvatarImageSet,
      school: user.school,
      grade: user.grade,
      major: user.major
    }));

    res.status(200).json({ following: formattedFollowing });
  } catch (error) {
    res.status(500).json({ message: '获取关注列表失败', error: error.message });
  }
});

module.exports = router;
